package com.zzyl.framework.interceptor;

import cn.hutool.http.HttpRequest;
import com.zzyl.common.constant.HttpStatus;
import com.zzyl.common.utils.StringUtils;
import com.zzyl.common.utils.UserThreadLocal;
import com.zzyl.framework.web.service.TokenService;
import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 小程序端拦截器
 *
 * @Author mr.lcc
 * @Data 2025/5/25 9:30
 */
@Component
@Slf4j
public class MemberInterceptor implements HandlerInterceptor {

    @Autowired
    private TokenService tokenService;

    /**
     * 请求到控制器之前拦截
     *
     * @param request
     * @param response
     * @param handler
     * @return
     * @throws Exception
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 1.判断是否是非资源请求，如果不是controller资源，直接放行。
        boolean result = handler instanceof HandlerMethod;
        if (!result) {
            return true;
        }

        // 2.获取用户token信息
        String token = request.getHeader(HttpHeaders.AUTHORIZATION);

        // 3.如果为空，返回401错误码，返回错误信息。
        if (StringUtils.isBlank(token)) {
            response.setStatus(HttpStatus.UNAUTHORIZED);
            throw new RuntimeException("非法token，请登录");
        }

        // 4.解析token信息（需要try）
        try {
            Claims claims = tokenService.parseToken(token);
            if (claims == null) {
                response.setStatus(HttpStatus.UNAUTHORIZED);
                throw new RuntimeException("非法token，请登录");
            }
            // 5.解析用户信息，得到用户id
            long userId = Long.parseLong(String.valueOf(claims.get("userId")));
            log.info("当前线程用户id：{}", userId);

            // 6.设置用户信息到ThreadLocal中
            UserThreadLocal.set(userId);
        } catch (RuntimeException e) {
            // 7.返回401错误码，返回错误信息。
            response.setStatus(HttpStatus.UNAUTHORIZED);
            throw new RuntimeException("解析Token失败！，请检查");
        }

        // 8.放行
        return true;
    }

    /**
     * 响应视图前拦截
     *
     * @param request
     * @param response
     * @param handler
     * @param ex
     * @throws Exception
     */
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        log.info("清除用户信息");
        UserThreadLocal.remove();
    }
}
